﻿var key = '12345678';
var userId = localStorage.getItem("parkId");
var code, extCode;
var oldAccessList = [];

$(function () {
    getContractType();//获取合同类型
    getRoleList();//获取角色列表
    getAccessList();//获取门禁列表
    getVideoGroupList();//获取视频门禁组
});

//获取合同类型
function getContractType() {
    // PostForm("/cwp/front/sh/dict!execute", "uid=D012&dictKey=contract_type", "", function(result){
    //     if (result.returnCode == "0" && result.beans.length > 0) {
    //         for (var i = 0; i < result.beans.length; i++) {
    //             option = "<option value='" + result.beans[i].dictdataKey + "'>" + result.beans[i].dictdataName + "</option>";
    //             $("#contractType").append(option);
    //         }
    //     }
    // }, '');
    $.getJSON('/cwp/src/json/user/user_dict_D012.json',function(result){
        if (result.returnCode == "0" && result.beans.length > 0) {
            for (var i = 0; i < result.beans.length; i++) {
                option = "<option value='" + result.beans[i].dictdataKey + "'>" + result.beans[i].dictdataName + "</option>";
                $("#contractType").append(option);
            }
        }
    })
}

//点击新增按钮调用事件
function addUser(type) {
    internalUserModal();//启用用户模态框——内部
    $("#userType").attr("disabled", "disabled");//用户类型不可选
    code = "add";//调用新增验证
    $(".t-tag-category").removeClass("selected");//清空角色、门禁、视频列表选项
    selectService();//显示部门或服务公司
    $("#hiddend").val("add");//新增
    $("#hidRole").val("");//角色清空
    $("#trueName").val("");//姓名
    $("#phone").val("");//手机
    $("#phone").attr("disabled", false);
    //$("#phone")[0].readOnly = false;
    $("#oldPhone").val("");
    $("#boy")[0].checked = true;//性别
    $("#girl")[0].checked = false;
    $("#email").val("");//邮箱
    $("#cardNo").val("");//一卡通编号
    $("#oldCardNo").val("");
    //身份证号
    $("#identityCard").val("");
    $("#oldIdentityCard").val("");
    $("#identityCard").attr("disabled", false);
    //$("#identityCard")[0].readOnly = false;
    //if (type == "0") {//新增内部用户
    //用户名
    $("#parkId").val("");
    $("#userName").val("");
    $("#oldUserName").val("");
    $("#userName")[0].readOnly = false;
    //员工编号
    $("#emloyeeNo").val("");
    $("#emloyeeNo")[0].readOnly = false;
    $("#oldEmloyeeNo").val("");
    //部门
    $("#dept").empty();
    $("#deptText").val("");
    $("#contractType").val("");//合同类型
    //} else {//新增外部用户
    //服务公司
    $("#companyId").empty();
    //}
    if (type == "0") {
        $("#exampleModalLabel").html("新增内部用户");
        $("#userType").val("0");//用户类型
        $(".insidePart").show();//显示内部用户信息
        $(".outsidePart").hide();//隐藏外部用户信息
        //内部用户表单验证
        userValidtor();
        insideValidtor();
    } else {
        $("#exampleModalLabel").html("新增外部用户");
        $("#userType").val("1");//用户类型
        $(".insidePart").hide();//隐藏内部用户信息
        $(".outsidePart").show();//显示外部用户信息
        //外部用户表单验证
        userValidtor();
        outerValidtor();
    }
}

//新增内部用户
$("#btnAddUser").on("click", function () {
    addUser("0");
});
//新增外部用户
$("#btnAddUserService").on("click", function () {
    addUser("1");
});

//启用内部用户模态框
function internalUserModal() {
    $(".tipArea div").html("").attr("class", "");
    $(".userInfo-tab li:eq(0) a").tab('show');
    $("#modalAddUser").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
    //.on('show.bs.modal', centerModal());
    //$(window).on('resize', centerModal());
}

//显示部门或服务公司
function selectService() {
    var selectTab = $('#myTabs .active .isSelect').attr("id");
    if (selectTab == 0) {
        // PostForm("/cwp/front/sh/dept!execute", "uid=c001", "", successResultDept, '');
        $.getJSON('/cwp/src/json/user/user_dept_c001.json',function(data){
            successResultDept(data);
        })
    } else {
        // PostForm("/cwp/front/sh/company!execute", "uid=c006", "", successResultVendor, '');
        $.getJSON('/cwp/src/json/user/user_company_c006.json',function(data){
            successResultVendor(data);
        })
    }
}

//查询部门成功回调函数
function successResultDept(result) {
    if (result.returnCode == '0') {

        var dept = localStorage.getItem("department");
        var option = "<option value=''>请选择</option>";
        $('#deptId').empty();
        for (var i = 0; i < result.beans.length; i++) {
            var department = result.beans[i];
            var deptId = department.deptId;
            var deptName = department.deptName;
            if (dept == deptId) {
                var str = "<option value='" + deptId + "' selected='selected'>" + deptName + "</option>"
            } else {
                var str = "<option value='" + deptId + "'>" + deptName + "</option>"
            }
            option += str;
        }
        //if (removeToIn){
        //$("#removeDeptId").append(option);
        //}else{
        $("#deptId").append(option);
        //}
        localStorage.removeItem("department");
    }
}

//查询服务公司成功回调函数
function successResultVendor(result) {
    var optionList = "";
    if (result.returnCode == '0') {

        var companyNo = localStorage.getItem("companyId");
        optionList = "<option name='' value=''>--请选择--</option>";
        for (var i = 0; i < result.beans.length; i++) {
            var company = result.beans[i];
            var companyId = company.companyId;
            var companyName = company.companyName;
            if (companyNo == companyId) {
                var str = "<option value='" + companyId + "' selected='selected'>" + companyName + "</option>"
            } else {
                var str = "<option value='" + companyId + "'>" + companyName + "</option>"
            }
            optionList += str;
        }
        $("#companyId").append(optionList);
        localStorage.removeItem("companyId");
    }
}


//编辑按钮
function updateUserInfo(parkId) {
    code = "update";
    // 清空选中列表
    $(".t-tag-category").removeClass("selected");
    // PostForm("/cwp/front/sh/user!execute", "uid=u001&parkId=" + parkId, "", successResultupdate, '');
    $.getJSON('/cwp/src/json/user/user_update_u001.json',function(data){
        successResultupdate(data);
    })
}

//获取所有角色
function getRoleList() {
    // PostForm("/cwp/front/sh/role!execute", "uid=c008", "", function(result){
    //     if (result.returnCode == "0") {
    //         if (result.beans.length > 0) {
    //             $(".modal-footer").show();
    //             var outHtml = template("roleTmpl", result.beans);
    //             $(".role-list").html(outHtml);
    //         }
    //         else {
    //             $(".role-list").html("<div class='tip'>暂无角色数据</div>");
    //         }
    //     }
    //     else {
    //         $(".role-list").html("<div class='tip'>暂无角色数据</div>");
    //     }
    // }, '',"frm");
    $.getJSON('/cwp/src/json/user/user_role_c008.json',function(result){
        if (result.returnCode == "0") {
            if (result.beans.length > 0) {
                $(".modal-footer").show();
                var outHtml = template("roleTmpl", result.beans);
                $(".role-list").html(outHtml);
            }
            else {
                $(".role-list").html("<div class='tip'>暂无角色数据</div>");
            }
        }
        else {
            $(".role-list").html("<div class='tip'>暂无角色数据</div>");
        }
    })
}
//读取、清空、恢复门禁权限
function accessOperat(url,parkId,successCb){
    // PostForm("/cwp/front/sh/ccac!execute", "uid=ccac001&placeId=9&url="+url+"&parkId="+parkId, "", function (result) {
    //     successCb && successCb(result);
    // }, "","frm");
    $.getJSON('/cwp/src/json/user/user_ccac_ccac001.json',function(result){
        successCb && successCb(result);
    })
}
//修改用户-请求成功回调函数
function successResultupdate(result) {
    //读取被选中的角色、门禁权限、视频列表
    defaultSelectedList(result.object.parkId);
    //启用用户模态框——内部
    internalUserModal();
    //清空角色、门禁、视频选中
    $(".access .t-tag-category").attr("class", "t-tag-category");
    switch (result.returnCode) {
        case "0":
            $("#phone").attr("disabled", true);
            $("#identityCard").attr("disabled", true);
            $("#parkId").val(result.object.parkId);
            //身份证号
            $("#identityCard").val(result.object.identityCard);
            $("#oldIdentityCard").val(result.object.identityCard);
            $("#oldicDES").val(result.object.identityCardDES);
            var userRole = localStorage.getItem("roles");
            var roleArr = JSON.parse(userRole);
            for(var i=0 ; i<roleArr.length ; i++){
                if (roleArr[i].roleId == 55) {//制卡员ID55——可编辑手机和身份证号
                    //$("#phone")[0].readOnly = false;
                    $("#phone").attr("disabled", false);
                    //身份证号
                    //$("#identityCard")[0].readOnly = true;
                    //$("#identityCard").attr("disabled", false);
                    //解密
                    // var cardNum = decryptByDES(result.object.identityCardDES, key);
                    // $("#identityCard").val(cardNum);
                    // $("#oldIdentityCard").val(result.object.identityCard);
                    // $("#oldicDES").val(result.object.identityCardDES);
                }
            }
            $("#hiddend").val("update");//编辑
            $("#userType").attr("disabled", false)//用户类型可选
            //姓名
            $("#trueName").val(result.object.trueName);
            //手机
            $("#phone").val(result.object.phone);
            $("#oldPhone").val(result.object.phone);
            //性别
            if (result.object.sex == "0") {
                $("#boy")[0].checked = true;
            } else {
                $("#girl")[0].checked = true;
            }
            //邮箱
            $("#email").val(result.object.email);
            //一卡通编号
            $("#cardNo").val(result.object.cardNo);
            $("#oldCardNo").val(result.object.cardNo);
            var selectTab = $('#myTabs .active .isSelect').attr("id");
            extCode = "update";
            if (selectTab == '0') {//编辑内部用户
                $("#exampleModalLabel").html("编辑内部用户");
                $("#userType").val("0");
                $(".insidePart").show();//显示内部用户信息
                $(".outsidePart").hide();//隐藏外部用户信息

                //用户名
                $("#userName").val(result.object.userName);
                $("#userName")[0].readOnly = true;
                $("#oldUserName").val(result.object.userName);
                //员工编号
                $("#emloyeeNo").val(result.object.emloyeeNo);
                $("#oldEmloyeeNo").val(result.object.emloyeeNo);
                //合同类型
                $("#contractType").val(result.object.contractType);
                //部门
                $("#deptText").val(result.object.department);
                $("#deptId").val(result.object.deptId);
                //内部用户验证
                userValidtor();
                insideValidtor();
            } else {
                $("#exampleModalLabel").html("编辑外部用户");
                $("#userType").val("1");
                $(".insidePart").hide();//显示内部用户信息
                $(".outsidePart").show();//隐藏外部用户信息
                $("#emloyeeNo").val('-1');
                /*$("#oldEmloyeeNo").val('-1');*/
                if (result.object.isChinamobile == 0) {
                    //$("#deptService").empty();
                    //$("#deptService").attr("name", "deptId");
                    $("#departService").html("部门");
                    localStorage.setItem("department", result.object.deptId);
                    // PostForm("/cwp/front/sh/dept!execute", "uid=c001", "", successResultDept, '');
                    $.getJSON('/cwp/src/json/user/user_dept_c001.json',function(result){
                        successResultDept(result);
                    })
                } else {
                    // $("#no")[0].checked = true;
                    //$("#deptService").empty();
                    //$("#deptService").attr("name", "companyId");
                    var span = $('<span/>').text('*').addClass('t-tip-verification');
                    $("#departService").html(span);
                    $("#departService").append('服务公司')
                    localStorage.setItem("companyId", result.object.companyId);
                    // PostForm("/cwp/front/sh/company!execute", "uid=c006", "", successResultVendor, '');
                    $.getJSON('/cwp/src/json/user/user_company_c006.json',function(result){
                        successResultVendor(result);
                    })
                }
                //外部用户验证
                userValidtor();
                outerValidtor();
            }
            break;
        case "1":
        case "2":
            showTipBox('tip_error', 'down_arrow', result.returnMessage, 'login_name');
            break;
        case "-9999":
            showTipBox('tip_error', 'down_arrow', "请求失败", 'login_name');
            break;
        default:
            break;
    }
}

//用户类型的change事件
$("#userType").change(function () {
    var selectTab = $('#myTabs .active .isSelect').attr("id");
    if (selectTab == "0" && $(this).val() == "1") {
        //服务公司
        $("#companyId").empty();
    }
    if (selectTab == "1" && $(this).val() == "0") {
        //用户名
        $("#userName").val("");
        $("#oldUserName").val("");
        $("#userName")[0].readOnly = false;
        //员工编号
        $("#emloyeeNo").val("");
        $("#emloyeeNo")[0].readOnly = false;
        $("#oldEmloyeeNo").val("");
        //部门
        $("#dept").empty();
        $("#deptText").val("");
        //合同类型
        $("#contractType").val("");
    }
    if ($(this).val() == "0") {//内部用户
        $(".insidePart").show();//显示内部用户信息
        $(".outsidePart").hide();//隐藏外部用户信息
        //内部用户表单验证
        userValidtor();
        insideValidtor();
    } else {//外部用户
        $(".insidePart").hide();//显示内部用户信息
        $(".outsidePart").show();//隐藏外部用户信息
        //获取服务公司列表
        // PostForm("/cwp/front/sh/company!execute", "uid=c006", "", successResultVendor, '');
        $.getJSON('/cwp/src/json/user/user_company_c006.json',function(result){
            successResultVendor(result);
        })
        //外部用户表单验证
        userValidtor();
        outerValidtor();
    }
});

// 默认选中
function defaultSelectedList(id) {
    // 员工类型
    // PostForm("/cwp/front/sh/user!execute", "uid=u010&staffId=" + id, "", function (result) {
    //     if (result.beans != undefined && result.beans != null) {
    //         for (var i = 0; i < result.beans.length; i++) {//选中角色赋值
    //             $("#roleList" + result.beans[i].roleId).addClass("selected");
    //         }
    //     }
    // }, '', 'frm');
    $.getJSON('/cwp/src/json/user/user_role_u010.json',function(result){
        if (result.beans != undefined && result.beans != null) {
            for (var i = 0; i < result.beans.length; i++) {//选中角色赋值
                $("#roleList" + result.beans[i].roleId).addClass("selected");
            }
        }
    })
    //门禁权限
    oldAccessList = [];
    accessOperat("/PlaceAcsGroupName/queryAccessGroups",id,function(result){
        if (result.beans != undefined && result.beans != null) {
            for (var i = 0; i < result.beans.length; i++) {//门禁权限选中项赋值
                if(result.beans[i].area == "1"){
                    $("#accessId" + result.beans[i].id).addClass("selected");
                    oldAccessList.push(result.beans[i].sysIdAndGrouId);
                }
            }
        }
    })
    // 视频
    // PostForm("/cwp/front/sh/videoGroup!execute", "uid=v010&parkUserId=" + id, "", function (result) {
    //     if (result.object != undefined && result.object != null) {
    //         for (var i = 0; i < result.object.length; i++) {//选中角色赋值
    //             $("#videoList" + result.object[i]).addClass("selected");
    //         }
    //     }
    // }, '', 'frm');
    $.getJSON('/cwp/src/json/user/user_videoGroup_v010.json',function(result){
        if (result.object != undefined && result.object != null) {
            for (var i = 0; i < result.object.length; i++) {//选中角色赋值
                $("#videoList" + result.object[i]).addClass("selected");
            }
        }
    })
}

//新增内部用户表单验证方法
function userValidtor() {
    $.formValidator.initConfig({
        validatorGroup: "0",
        formid: "frmMain", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });
    //姓名
    $("#trueName").formValidator({
        validatorGroup: "0",
        onfocus: "请输入姓名",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 20,
        onempty: "请输入姓名",
        onerror: "姓名长度只能在4-8位字符之间"
    }).RegexValidator({
        regexp: "realname",
        datatype: "enum",
        onerror: "姓名只能为汉字或英文"
    });
    //手机
    $("#phone").formValidator({
        validatorGroup: "0",
        onfocus: "请输入手机号",
        oncorrect: " "
    }).InputValidator({
        min: 11,
        max: 11,
        onempty: "请输入手机号",
        onerror: "手机号码长度为11位"
    }).RegexValidator({
        regexp: "mobile",
        datatype: "enum",
        onerror: "手机号码格式无效"
    }).FunctionValidator({
        fun: function (val, elem) {
            var oldPhone = $("#oldPhone").val();
            if (val == oldPhone) {
                return true;
            }
            else {
                // var htmlObj = $.ajax({
                //     type: "post",
                //     url: "/cwp/front/sh/user!execute",
                //     beforeSend: function (requests) {
                //         requests.setRequestHeader("platform", "pc");
                //     },
                //     async: false,
                //     dataType: "json",
                //     data: {
                //         uid: "u008",
                //         userId: userId,
                //         phone: $("#phone").val()
                //     }
                // });
                // var result = JSON.parse(htmlObj.responseText);
                $.getJSON('/cwp/src/json/user/user_update_u001.json',function(result){
                    if (result.returnCode == "0") {
                        return true;
                    } else {
                        return "该手机号已添加";
                    }
                })
            }
        }
    });
    //性别
    //邮箱
    $("#email").formValidator({
        validatorGroup: "0",
        empty: true,
        onshow: "请输入邮箱",
        onfocus: "请输入邮箱",
        onempty: "",
        oncorrect: " "
    }).RegexValidator({
        regexp: "email",
        datatype: "enum",
        onerror: "请输入正确的邮箱"
    })//.DefaultPassed();
    //一卡通编号
    $("#cardNo").formValidator({
        validatorGroup: "0",
        onshow: "请输入一卡通编号",
        onfocus: "请输入一卡通编号",
        oncorrect: "&nbsp;"
    }).InputValidator({
        min: 8,
        max: 20,
        onempty: "请输入一卡通编号",
        onerror: "一卡通编号的长度为8-20个字符" //'HAHA'
    }).RegexValidator({
        regexp: "cardNo",
        datatype: "enum",
        onerror: "请输入正确的一卡通编号"
    }).FunctionValidator({
        fun: function (val, elem) {
            var oldCardNo = $("#oldCardNo").val();
            if (val == oldCardNo) {
                return true;
            }
            else {
                // var htmlObj = $.ajax({
                //     type: "post",
                //     url: "/cwp/front/sh/user!execute",
                //     beforeSend: function (requests) {
                //         requests.setRequestHeader("platform", "pc");
                //     },
                //     async: false,
                //     dataType: "json",
                //     data: {
                //         uid: "u008",
                //         userId: userId,
                //         cardNo: $("#cardNo").val()
                //     }
                // });
                // var result = JSON.parse(htmlObj.responseText);
                $.getJSON('/cwp/src/json/user/user_update_u001.json',function(result){
                    if (result.returnCode == "0") {
                        return true;
                    } else {
                        return "该一卡通编号已添加";
                    }
                })
            }
        }
    });
    //身份证号
    if (code == "add") {//新增
        $("#identityCard").formValidator({
            validatorGroup: "0",
            onshow: "请输入身份证号",
            onfocus: "请输入身份证号",
            oncorrect: "&nbsp;"
        }).InputValidator({
            min: 18,
            max: 18,
            onempty: "请输入身份证号",
            onerror: "身份证号长度为18位"
        }).RegexValidator({
            regexp: "idcard",
            datatype: "enum",
            onerror: "请输入正确的身份证号"
        }).FunctionValidator({
            fun: function (val, elem) {
                var oldIdNum = $("#oldIdentityCard").val();
                var idCardValIn = $("#identityCard").val();
                var idCardDESIn = EncryptIDCARD(idCardValIn);
                if (val == oldIdNum) {
                    return true;
                }
                else {
                    // var htmlObj = $.ajax({
                    //     type: "post",
                    //     url: "/cwp/front/sh/user!execute",
                    //     beforeSend: function (requests) {
                    //         requests.setRequestHeader("platform", "pc");
                    //     },
                    //     async: false,
                    //     dataType: "json",
                    //     data: {
                    //         uid: "u008",
                    //         userId: userId,
                    //         identityCard: idCardDESIn
                    //     }
                    // });
                    // var result = JSON.parse(htmlObj.responseText);
                    $.getJSON('/cwp/src/json/user/user_update_u001.json',function(result){
                        if (result.returnCode == "0") {
                            return true;
                        } else {
                            return result.returnMessage;
                        }
                    })
                }
            }
        });
    }else {//不编辑
        $("#identityCard").formValidator({
            validatorGroup: "0",
            onshow: "请输入身份证号",
            onfocus: "请输入身份证号",
            oncorrect: "&nbsp;"
        }).InputValidator({
            min: 0,
            max: 18,
            onempty: "请输入身份证号",
            onerror: "身份证号长度为18位"
        });
    }
    $("#hidRole").formValidator({
        validatorGroup: "0",
        onfocus: "请选择角色",
        oncorrect: "&nbsp;"
    }).InputValidator({
        min: 1,
        onempty: "请选择角色",
        onerror: "请选择角色"
    });
}
function insideValidtor(){//内部用户验证方法
    $.formValidator.initConfig({
        validatorGroup: "1",
        formid: "frmMain", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });
    //用户名
    $("#userName").formValidator({
        validatorGroup: "1",
        onfocus: "用户名为姓名全拼",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 20,
        onempty: "请输入用户名",
        onerror: "用户名长度为4-20个字符"
    }).RegexValidator({
        regexp: "letter_n",
        datatype: "enum",
        onerror: "使用姓名全拼或1-2位数字结尾"
    }).FunctionValidator({
        fun: function (val, elem) {
            var oldUserName = $("#oldUserName").val();
            if (val == oldUserName) {
                return true;
            }
            else {
                // var htmlObj = $.ajax({
                //     type: "post",
                //     url: "/cwp/front/sh/user!execute",
                //     beforeSend: function (requests) {
                //         requests.setRequestHeader("platform", "pc");
                //     },
                //     async: false,
                //     dataType: "json",
                //     data: {
                //         uid: "u008",
                //         userId: userId,
                //         userName: $("#userName").val()
                //     }
                // });
                // var result = JSON.parse(htmlObj.responseText);
                $.getJSON('/cwp/src/json/user/user_update_u001.json',function(result){
                    if (result.returnCode == "0") {
                        return true;
                    } else {
                        return "该用户名已添加";
                    }
                })
            }
        }
    });
    //员工编号
    $("#emloyeeNo").formValidator({
        validatorGroup: "1",
        onfocus: "请输入员工编号",
        oncorrect: " "
    }).InputValidator({
        min: 4,
        max: 20,
        onempty: "请输入员工编号",
        onerror: "员工编号长度为4-20个字符"
    }).FunctionValidator({
        fun: function (val, elem) {
            var oldEmloyeeNo = $("#oldEmloyeeNo").val();
            if (val == oldEmloyeeNo) {
                return true;
            }
            else {
                // var htmlObj = $.ajax({
                //     type: "post",
                //     url: "/cwp/front/sh/user!execute",
                //     beforeSend: function (requests) {
                //         requests.setRequestHeader("platform", "pc");
                //     },
                //     async: false,
                //     dataType: "json",
                //     data: {
                //         uid: "u008",
                //         userId: userId,
                //         emloyeeNo: $("#emloyeeNo").val()
                //     }
                // });
                // var result = JSON.parse(htmlObj.responseText);
                $.getJSON('/cwp/src/json/user/user_update_u001.json',function(result){
                    if (result.returnCode == "0") {
                        return true;
                    } else {
                        return "该员工编号已添加";
                    }
                })
            }
        }
    });
    //部门
    $("#deptText").formValidator({
        validatorGroup: "1",
        onfocus: "部门必须选择",
        oncorrect: "&nbsp;"
    }).InputValidator({
        min: 1,
        onempty: "请选择部门",
        onerror: "请选择部门"
    });
    //合同类型
    $("#contractType").formValidator({
        validatorGroup: "1",
        onfocus: "请选择合同类型",
        oncorrect: "&nbsp;"
    }).InputValidator({
        min: 1,
        onempty: "请选择合同类型",
        onerror: "请选择合同类型"
    });

}
function outerValidtor(){//内部用户验证方法
    $.formValidator.initConfig({
        validatorGroup: "2",
        formid: "frmMain", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });
    //服务公司
    $("#companyId").formValidator({
        validatorGroup: "2",
        onfocus: "请选择服务公司",
        oncorrect: "&nbsp;"
    }).InputValidator({
        min: 1,
        onempty: "请选择服务公司",
        onerror: "请选择服务公司"
    });
}
//加密
function encryptByDES(message, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}

function EncryptIDCARD(word) {
    var key = CryptoJS.enc.Utf8.parse("wp.onlinecmcc.cn");
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
}

//DES 解密
function decryptByDES(ciphertext, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    // direct decrypt ciphertext
    var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    }, keyHex, {
        mode: CryptoJS.mode.ECB
        //这一步 是来填写 加密时候填充方式 padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
}

//编辑用户保存事件
function editSave(side, departName, cardNum,RoleArry) {
    // var parkId = $("#parkId").val();  //当前记录标识UUID——用户名
    // var dataJson = {
    //     uid: 'u024',
    //     userId: userId,
    //     trueName: $('#trueName').val(),
    //     cardNo: $('#cardNo').val(),
    //     phone: $('#phone').val(),
    //     sex: $("input[name='sex']:checked").val(),
    //     identityCard: cardNum,
    //     deptName: departName
    // };
    //var CardDESNum = $("#oldicDES").val();
    // if ($("#oldicDES").val() != encryptByDES($('#identityCard').val(), key)) {//没改变原来的值,不传参
    //     CardDESNum = encryptByDES($("#identityCard").val());
    // }
    // $.ajax({
    //     url: '/cwp/front/sh/user!execute',
    //     data: dataJson,
    //     type: 'post',
    //     beforeSend: function (requests) {
    //         requests.setRequestHeader("platform", "pc");
    //         $("#myTip .tip-info").html('处理中，请稍候...');
    //         $("#myTip #icon-tip").removeClass();
    //         $("#myTip").modal({
    //             keyboard: false,
    //             backdrop: 'static'
    //         }).on('show.bs.modal', centerModal());
    //     },
    //     success: function (res) {
    //         if (res.returnCode == '0') {
    //
    //             var middlemanToken = res.bean.middlemanToken;
    //             if (middlemanToken == "undefined") {
    //                 middlemanToken = " ";
    //             }
    //             //角色信息保存-包含关闭模态框操作  成功回调里面 保存门禁权限、视频组
    //             PostForm("/cwp/front/sh/user!execute", "uid=u004&parkId=" + parkId + "&addRole=" + RoleArry + "&isChinamobile=" + side + "&lastModifier=" + userId + "&middlemanToken=" + middlemanToken, "post", successResultSaveUser, "", "frmMain");
    //
    //         } else {
    //             if (side == "0") {
    //                 tipModal('icon-cross', res.returnMessage);
    //             } else {
    //                 tipModal('icon-cross', res.returnMessage, "", 2e3);
    //             }
    //         }
    //     },
    //     error: function () {
    //         _self.removeAttr('disabled');
    //         _self.text('保存');
    //         $("#myTip").modal("hide");
    //     }
    // })
    $.getJSON('/cwp/src/json/user/user_u004.json',function(data){
        successResultSaveUser(data);
    })
}

//新增用户保存事件
function addSave(side, departName, cardNum,RoleArry) {
    // var dataJson = {
    //     uid: 'u024',
    //     userId: userId,
    //     trueName: $('#trueName').val(),
    //     cardNo: $('#cardNo').val(),
    //     phone: $('#phone').val(),
    //     sex: $("input[name='sex']:checked").val(),
    //     identityCard: cardNum,
    //     deptName: departName
    // };
    // $.ajax({
    //     url: '/cwp/front/sh/user!execute',
    //     data: dataJson,
    //     type: 'post',
    //     beforeSend: function (requests) {
    //         requests.setRequestHeader("platform", "pc");
    //         $("#myTip .tip-info").html('处理中，请稍候...');
    //         $("#myTip #icon-tip").removeClass();
    //         $("#myTip").modal({
    //             keyboard: false,
    //             backdrop: 'static'
    //         }).on('show.bs.modal', centerModal());
    //     },
    //     success: function (res) {
    //         if (res.returnCode == '0') {
    //             var middlemanToken = res.bean.middlemanToken;
    //             if (middlemanToken == "undefined") {
    //                 middlemanToken = " ";
    //             }
    //             //角色信息保存  成功回调里（取用户id）保存门禁权限、视频组
    //             PostForm("/cwp/front/sh/user!execute", "uid=u003&addRole=" + RoleArry + "&isChinamobile=" + side + "&creator=" + userId + "&middlemanToken=" + middlemanToken, "post", successResultSaveUser, "", "frmMain");
    //
    //         } else {
    //             tipModal('icon-cross', res.returnMessage, "", 2e3);
    //         }
    //     },
    //     error: function () {
    //         _self.removeAttr('disabled');
    //         _self.text('保存')
    //     }
    // })
    $.getJSON('/cwp/src/json/user/user_ccac_ccac001.json',function(result){
        if (result.returnCode == '0') {
            tipModal("icon-checkmark", "保存成功");
            //关闭模态框
            $("#modalAddUser").modal("hide");
            //添加成功后重新加载用户列表
            isPostBack = true;
            searchUserList(1);
        } else {
            tipModal("icon-cross", res.returnMessage);
        }
    })
}

//新增、编辑客户保存按钮点击事件
$("#btn_saveUser").on("click", function () {
    code = $("#hiddend").val();//判断是新增操作还是修改操作标识
    var deptName = $("#deptText").val();//部门
    var ic = $('#identityCard').val();//身份证号
    var icDES = encryptByDES(ic, key);
    var oldicDES = $("#oldicDES").val();
    // if (!$("#identityCard").attr("disabled")){//可编辑身份证
    //     oldicDES = icDES;
    // }
    //var idCardDESIn = EncryptIDCARD(ic);
    // if (oldicDES == encryptByDES(ic, key)) {//没改变原来的值,不传参
    //     oldicDES = "";
    // }
    var depart = $("#companyId").find("option:selected").text();//服务公司
    //获取已选中的角色信息
    var RoleArry = [];
    $('#userInfoTab1 .t-tag-category.selected').each(function () {
        var id = $(this).attr("data-id");
        RoleArry.push(id);
    });
    $("#hidRole").val(RoleArry);
    // var _self = $(this);

    if (code == "update") {
        //修改用户信息
        $('#isChinamobile').val('0');//显示部门还是服务公司
        var selectTab = $('#myTabs .active .isSelect').attr("id");
        var userType = $("#userType").val();
        switch(userType){
            case "0"://内部用户验证
                if(!$.formValidator.PageIsValid(0) && !$.formValidator.PageIsValid(1)){
                    return false;
                }else if(!$.formValidator.PageIsValid(0)){
                    return false;
                }else if(!$.formValidator.PageIsValid(1)){
                    return false;
                }
                break;
            case "1"://外部用户验证
                if(!$.formValidator.PageIsValid(0) && !$.formValidator.PageIsValid(2)){
                    return false;
                }else if(!$.formValidator.PageIsValid(0)){
                    return false;
                }else if(!$.formValidator.PageIsValid(2)){
                    return false;
                }
                break;
        }
        if (selectTab == userType) {//无转移部门的用户编辑
            if (userType == "0") {
                editSave(0, deptName, oldicDES, RoleArry);//内部用户编辑保存
            } else {
                editSave(1, depart, oldicDES, RoleArry);//外部用户编辑保存
            }
        } else {//有转移部门的用户编辑
            if (userType == "0") {//外部用户转移到内部用户
                editSave(0, deptName, oldicDES, RoleArry);//内部用户编辑保存
            } else {//内部用户转移到外部用户
                editSave(1, depart, oldicDES, RoleArry);//外部用户编辑保存
            }
        }
    } else {//add
        var selectTab = $('#myTabs .active .isSelect').attr("id");
        if (selectTab == "0") {//内部用户新增
            if(!$.formValidator.PageIsValid(0) && !$.formValidator.PageIsValid(1)){
                return false;
            }else if(!$.formValidator.PageIsValid(0) || !$.formValidator.PageIsValid(1)){
                return false;
            }
            addSave(0, deptName, icDES, RoleArry);
        } else {//外部用户新增
            if(!$.formValidator.PageIsValid(0) && !$.formValidator.PageIsValid(2)){
                return false;
            }else if(!$.formValidator.PageIsValid(0) || !$.formValidator.PageIsValid(2)){
                return false;
            }
            addSave(1, depart, icDES, RoleArry);
        }
    }
});

function successResultSaveUser(result) {
    switch (result.returnCode) {
        case "0":
            //门禁、视频权限保存
            saveAccess(result);
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "保存失败");
            break;
        default:
            break;
    }
}

//保存用户门禁权限、视频组
function saveAccess(result) {
    var requestType = 0;
    var formId = "frmMain";
    var parkId = "";
    //var emloyeeNo=$("#cardNo").val();
    //emloyeeNo = $("#cardNo").val();
    if (code == "update") {
        requestType = 1;
        parkId = $("#frmMain .parkId").val();
    }
    else {
        parkId = result.object.parkId;
    }
    //用户类型
    if($('#userType option:selected').val() == "1"){
        $("#emloyeeNo").val('-1');
    }
    //获取已选中视频组id组合
    var videoListArry = [];
    $('.videolist.videolistSingle .t-tag-category.selected').each(function () {
        var id = $(this).attr("data-id");
        videoListArry.push(id);
    });
    //新增和修改的时候 视频组保存
    // PostForm("/cwp/front/sh/videoGroup!execute", "uid=v007&parkUserId=" + parkId + "&idStr=" + videoListArry.toString(), "", function (result) {
    //     if (result.returnCode == 0) {
    //         //tipModal("icon-checkmark", "视频权限保存成功");
    //     } else {
    //         tipModal("icon-cross", "视频权限保存失败");
    //     }
    // }, "", "frm");
    $.getJSON('/cwp/src/json/user/user_videoGroup_v007.json',function(data){
        if (result.returnCode == 0) {
            //tipModal("icon-checkmark", "视频权限保存成功");
        } else {
            tipModal("icon-cross", "视频权限保存失败");
        }
    })
    //获取已选中门禁权限id组合
    var accessList = getAccessArr();
    //新增和修改的时候 门禁列表保存
    var accessList =  getAccessArr();//选中的门禁id组合
    if((requestType == 0 && accessList) || (requestType == 1 && oldAccessList != accessList)){//新增选了门禁或者编辑修改了门禁
        // PostForm("/cwp/front/sh/ccac!execute", "uid=ccac001&url=/AcsAuthorization/updateAuthority&placeId=9&parkId="+parkId+"&accessGroupIds="+accessList, "post", function(result){
        //     if (result.returnCode == '0') {
        //         tipModal("icon-checkmark", "保存成功");
        //         //关闭模态框
        //         $("#modalAddUser").modal("hide");
        //         //添加成功后重新加载用户列表
        //         isPostBack = true;
        //         searchUserList(1);
        //         //tipModal("icon-checkmark", "门禁权限保存成功");
        //     } else {
        //         tipModal("icon-cross", "门禁权限保存失败");
        //     }
        //
        // }, "", "frm");

        $.getJSON('/cwp/src/json/user/user_ccac_ccac001.json',function(result){
            if (result.returnCode == '0') {
                tipModal("icon-checkmark", "保存成功");
                //关闭模态框
                $("#modalAddUser").modal("hide");
                //添加成功后重新加载用户列表
                isPostBack = true;
                searchUserList(1);
                //tipModal("icon-checkmark", "门禁权限保存成功");
            } else {
                tipModal("icon-cross", "门禁权限保存失败");
            }
        })
    }else{
        tipModal("icon-checkmark", "保存成功");
        //关闭模态框
        $("#modalAddUser").modal("hide");
        //添加成功后重新加载用户列表
        isPostBack = true;
        searchUserList(1);
    }
}
//部门树
//获取部门列表
$(function () {
    initDeptTreeModal();
});

function initDeptTreeModal() {
    // PostForm("/cwp/front/sh/dept!execute", "uid=c007", "", getDeptTreeModal, '');
    $.getJSON('/cwp/src/json/user/user_dept_c007.json',function(data){
        getDeptTreeModal(data);
    })
}

//获取数据初始化部门树
function getDeptTreeModal(result) {
    if (result.returnCode == "0") {
        //配置组织结构树
        var setting = {
            view: {
                dblClickExpand: false,
                showIcon: false,                 //隐藏节点图标
                selectedMulti: false             //设置是否允许同时选中多个节点
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClickSelect
            }
        };
        var zNodes = JSON.parse(result.object);
        $.fn.zTree.init($("#treeOrgModal"), setting, zNodes);
    }
}

function beforeClickSelect(treeId, treeNode) {
    // var zTree = $.fn.zTree.getZTreeObj("treeOrgModal");
    $("#deptText").val(treeNode.name);
    $("#deptText").blur();
    $("#deptId").val(treeNode.id);
    hideMenu();
    return false;
}

$("#deptText").on("focus", function () {
    var ele = $(this).attr("name");
    showMenu(ele);
});

function showMenu(ele) {
    var deptIdObj = $('#' + ele);
    var deptIdOffset = $('#' + ele).offset();
    //$("#menuContent").slideDown("fast");
    $("#menuContent").css({
        left: deptIdOffset.left + "px",
        top: deptIdOffset.top + deptIdObj.outerHeight() + "px"
    }).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
}

function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}

function onBodyDown(event) {
    if (!(event.target.id == "deptText" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
        hideMenu();
    }
}

//批量修改部门
var selectUser = "";
$("#btnModifyDept").on("click", function () {
    selectUser = "";
    $(".chkUser").each(function (index, e) {
        if (e.checked == true) {
            selectUser += e.value + ",";
        }
    });
    //减去最后一个逗号
    selectUser = selectUser.substring(0, selectUser.length - 1);
    if (selectUser != "") {
        //启用modal ID
        $("#modalBatDept").modal({
            keyboard: true,
            backdrop: 'static'
        }).on('show.bs.modal');
    } else {
        tipModal("icon-cross", "请选择人员");
    }
});

//批量修改部门
$(function () {
    initModalBatDept();
});

function initModalBatDept() {
    // PostForm("/cwp/front/sh/dept!execute", "uid=c007", "", getModalBatDept, '');
    $.getJSON('/cwp/src/json/user/user_dept_c007.json',function(data){
        getModalBatDept(data);
    })
}

//获取数据初始化部门树
function getModalBatDept(result) {
    if (result.returnCode == "0") {
        //配置组织结构树
        var setting = {
            view: {
                dblClickExpand: false,
                showIcon: false,                 //隐藏节点图标
                selectedMulti: false             //设置是否允许同时选中多个节点
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClickModify
            }
        };
        var zNodes = JSON.parse(result.object);
        $.fn.zTree.init($("#treeDeptBat"), setting, zNodes);
    }
}

//部门树点击回调事件
var countTreeObj = "";

function beforeClickModify(treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeDeptBat");
    zTree.selectNode(treeNode);
    countTreeObj = treeNode;
    return false;
}

//确定按钮事件
$("#btnConfirmDept").on("click", function () {
    if (countTreeObj != "") {
        // PostForm("/cwp/front/sh/dept!execute", "uid=c011&toDept=" + countTreeObj.id + "&users=" + selectUser, "", batModifyDept, "", "frmMainDeptbat");
        $.getJSON('/cwp/src/json/user/user_dept_c011.json',function(data){
            batModifyDept(data);
        })
    }
    else {
        tipModal("icon-cross", "请选择部门");
    }
});

function batModifyDept(result) {
    if (result.returnCode == "0") {
        $("#modalBatDept").modal("hide");
        tipModal("icon-checkmark", "修改成功");
        isPostBack = true;
        searchUserList(1);
    }
    else if (result.returnCode == "-9999") {
        tipModal('icon-cross', "修改部门失败");
    }
    else {
        tipModal('icon-cross', result.returnMessage);
    }
}


//获取被选中门禁列表
var getAccessArr = function(){
    var accessArr=[];
    $(".access-list .t-tag-category.selected").each(function () {
        var id = $(this).attr("data-id");
        accessArr.push(id);
    });
    //return accessArr.join("-");
    return encodeURIComponent(accessArr.toString());
};

//获取门禁权限——门禁列表
function getAccessList() {
    // PostForm("/cwp/front/sh/ccac!execute", "uid=ccac001&url=/PlaceAcsGroupName/queryAccessGroups&placeId=9", "", function (result) {
    //     if (result.returnCode == "0") {
    //         if (result.beans.length > 0) {
    //             $(".modal-footer").show();
    //             var outHtml = template("accessTmpl", result.beans);
    //             $(".access-list").html(outHtml);
    //         }
    //         else {
    //             $(".access-list").html("<div class='tip'>暂无门禁组数据</div>");
    //         }
    //     }
    //     else {
    //         $(".access-list").html("<div class='tip'>暂无门禁组数据</div>");
    //     }
    // }, "","frm");

    $.getJSON('/cwp/src/json/user/user_ccac_ccac001.json',function(result){
        if (result.returnCode == "0") {
            if (result.beans.length > 0) {
                $(".modal-footer").show();
                var outHtml = template("accessTmpl", result.beans);
                $(".access-list").html(outHtml);
            }
            else {
                $(".access-list").html("<div class='tip'>暂无门禁组数据</div>");
            }
        }
        else {
            $(".access-list").html("<div class='tip'>暂无门禁组数据</div>");
        }
    })
}

var getVideoGroupList = function () {
    // PostForm("/cwp/front/sh/videoGroup!execute", "uid=v003&pageSize=100&currentPage=1&videoArea=", "", function (result) {
    //     if (result.returnCode == 0) {
    //         var oldBeans = [];
    //         var newBeans = [];
    //         if(result.beans.length>0){
    //             for(var i=0 ; i<result.beans.length ; i++){
    //                 if (result.beans[i].videoArea == 1) {
    //                     oldBeans.push(result.beans[i])
    //                 } else if (result.beans[i].videoArea == 2) {
    //                     newBeans.push(result.beans[i])
    //                 }
    //             }
    //         }
    //         template.helper('videoListTmpl', function (inp) {
    //             if (inp == 1) {
    //                 return "new";
    //             } else {
    //                 return "old";
    //             }
    //         });
    //         // 单个
    //         var outHtmlOld = template("videoListTmpl", oldBeans);
    //         var outHtmlNew = template("videoListTmpl", newBeans);
    //         $(".videolist.videolistSingle.videolistOld").html(outHtmlOld);
    //         $(".videolist.videolistSingle.videolistNew").html(outHtmlNew);
    //
    //         // 批量
    //         var outHtmlOldBatch = template("videoListBatchTmpl", oldBeans);
    //         var outHtmlNewBatch = template("videoListBatchTmpl", newBeans);
    //         $(".videolist.videolistBatch.videolistOld").html(outHtmlOldBatch);
    //         $(".videolist.videolistBatch.videolistNew").html(outHtmlNewBatch);
    //         // 视频组选中
    //         // $(".videolistTab").on("click", ".t-tag-category", function () {
    //         // 	if ($(this).hasClass("selected")) {
    //         // 		$(this).removeClass("selected");
    //         // 	}
    //         // 	else {
    //         // 		$(this).addClass("selected");
    //         // 	}
    //         // });
    //     } else {
    //         tipModal("icon-cross", result.returnMessage);
    //     }
    // }, "", "frm");
    $.getJSON('/cwp/src/json/user/user_videoGroup_v003.json',function(result){
        if (result.returnCode == 0) {
            var oldBeans = [];
            var newBeans = [];
            if(result.beans.length>0){
                for(var i=0 ; i<result.beans.length ; i++){
                    if (result.beans[i].videoArea == 1) {
                        oldBeans.push(result.beans[i])
                    } else if (result.beans[i].videoArea == 2) {
                        newBeans.push(result.beans[i])
                    }
                }
            }
            template.helper('videoListTmpl', function (inp) {
                if (inp == 1) {
                    return "new";
                } else {
                    return "old";
                }
            });
            // 单个
            var outHtmlOld = template("videoListTmpl", oldBeans);
            var outHtmlNew = template("videoListTmpl", newBeans);
            $(".videolist.videolistSingle.videolistOld").html(outHtmlOld);
            $(".videolist.videolistSingle.videolistNew").html(outHtmlNew);

            // 批量
            var outHtmlOldBatch = template("videoListBatchTmpl", oldBeans);
            var outHtmlNewBatch = template("videoListBatchTmpl", newBeans);
            $(".videolist.videolistBatch.videolistOld").html(outHtmlOldBatch);
            $(".videolist.videolistBatch.videolistNew").html(outHtmlNewBatch);
            // 视频组选中
            // $(".videolistTab").on("click", ".t-tag-category", function () {
            // 	if ($(this).hasClass("selected")) {
            // 		$(this).removeClass("selected");
            // 	}
            // 	else {
            // 		$(this).addClass("selected");
            // 	}
            // });
        } else {
            tipModal("icon-cross", result.returnMessage);
        }
    })
};

// 操作 冻结/解冻 状态
function freezeUser(parkId, cardNo, uid, userName,trueName) {
    var erroricon = document.getElementById("noneChecked");
    erroricon.style.display = "none";
    $("#hidUserId").val(parkId);
    $("#hideCarNo").val(cardNo);
    $("#hideUid").val(uid);
    $("#hideUserName").val(userName);
    $("#hideTrueName").val(trueName);
    freezeStatus = $("#status" + parkId);
    if (freezeStatus.html() == "正常") {
        $("#freeze-item .t-tag-category").addClass("selected");
        $("#freeze-item .frozen").text("冻结账号");
        $("#freeze-item .jurisdiction").text("清空门禁权限");
    } else {
        $("#freeze-item .t-tag-category").removeClass("selected");
        $("#freeze-item .frozen").text("解冻账号");
        $("#freeze-item .jurisdiction").text("恢复门禁权限");
    }
    $("#modalFreeze").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}
//冻结用户
var freezeStatus = new Object();
var freezeBtn = new Object();
//保存权限设置
$("#btnConfirmFreeze").on("click", function () {
    var userId = $("#hidUserId").val();
    var cardNo = $("#hideCarNo").val();
    var uidNo = $("#hideUid").val();
    var djArr = [];
    $("#freeze-item .t-tag-category.selected").each(function () {
        var id = $(this).attr("data-id");
        djArr.push(id);
    });
    if(djArr.length == 0){
        var erroricon = document.getElementById("noneChecked");
        if (freezeStatus.html() == "正常") {//清空门禁权限
            erroricon.innerHTML="请选择需要冻结的项目";
        } else {//解冻账户
            erroricon.innerHTML="请选择需要解冻的项目";
        }
        erroricon.style.display = "block";
        //tipModal("icon-cross", "请选择项目");
        return false;
    }else if(djArr.length == 1){
        switch(djArr[0]){
            case "0":
                //冻结
                freezeUserOpt(userId);
                break;
            case "1":
                //清空门禁权限
                clearAccess(userId, cardNo, uidNo);
                break;
        }
    }else if(djArr.length == 2){
        clearAccess2(userId, cardNo, uidNo);
    }
    // $("#modalFreeze").modal("hide");
});

function freezeUserOpt(parkId) {
    freezeStatus = $("#status" + parkId);
    freezeBtn = $("#operate" + parkId);
    freezeBtn.attr("disabled", true).addClass("btn-disabled");
    if (freezeStatus.html() == "正常") {//冻结账户
        // PostForm("/cwp/front/sh/user!execute", "uid=u005&parkId=" + parkId + "&code=1", "", successResultFreezeUser, '');
        $.getJSON('/cwp/src/json/user/user_u005.json',function(data){
            successResultFreezeUser(data);
        })
    } else {//解冻账户
        // PostForm("/cwp/front/sh/user!execute", "uid=u005&parkId=" + parkId + "&code=0", "", successResultFreezeUser, '');
        $.getJSON('/cwp/src/json/user/user_u005.json',function(data){
            successResultFreezeUser(data);
        })
    }
}

//请求成功回调函数
function successResultFreezeUser(result) {
    if (result.returnCode == "0") {
        if (freezeStatus.html() == "正常") {
            freezeStatus.html("冻结");
            freezeBtn.html("解冻").removeClass("t-btn-red");
            tipModal("icon-checkmark", "冻结成功");
        } else {
            freezeStatus.html("正常");
            freezeBtn.html("冻结").addClass("t-btn-red");
            tipModal("icon-checkmark", "解冻成功");
        }
        isPostBack = true;
        searchUserList(1);
    }
    else if (result.returnCode == "-9999") {
        tipModal("icon-cross", "修改失败");
    }
    else {
        tipModal("icon-cross", result.returnMessage);
    }
    freezeBtn.attr("disabled", false).removeClass("btn-disabled");
    $("#modalFreeze").modal("hide");
}
//恢复门禁权限成功回调
function successFrozen(parkId,code){
    PostForm("/cwp/front/sh/user!execute", "uid=u029&parkId=" + parkId + "&code=" + code, "", function (result) {
        if (result.returnCode != "0") {
            tipModal("icon-cross", "智能门禁保存失败");
        }
    });
}
//清空门禁权限
function clearAccess(userId, cardNo, uidNo) {
    if (freezeStatus.html() == "正常") {//清空门禁权限
        accessOperat("/AcsAuthorization/freezeAccess",userId,function(result){
            if (result.returnCode == "0") {
                //清空门禁成功回调
                successFrozen(userId,1);
                tipModal("icon-checkmark", "门禁权限清空成功");
                //清空成功后重新加载用户列表
                isPostBack = true;
                searchUserList(1);
            }else {
                tipModal("icon-cross", "门禁权限清空失败");
            }
        })
        freezeStatus = $("#status" + userId);
    } else {//恢复门禁权限
        accessOperat("/AcsAuthorization/unfreezeAccess",userId,function(result){
            if (result.returnCode == "0") {
                //恢复门禁成功回调
                successFrozen(userId,"0");
                tipModal("icon-checkmark", "门禁权限恢复成功")
                //恢复成功后重新加载用户列表
                isPostBack = true;
                searchUserList(1);
            }else {
                tipModal("icon-cross", "门禁权限恢复失败");
            }
        })
    }
    $("#modalFreeze").modal("hide");
}
//冻结或解冻时选择两项  先清空门禁权限  成功回调里再冻结账户
function clearAccess2(userId, cardNo, uidNo) {//冻结账号&清空门禁权限
    if (freezeStatus.html() == "正常") {//清空门禁权限
        accessOperat("/AcsAuthorization/freezeAccess",userId,function(result){
            if (result.returnCode == "0") {
                freezeUserOpt(userId);//冻结账号
            }else {
                tipModal("icon-cross", "门禁权限清空失败");
            }
        })
        freezeStatus = $("#status" + userId);
    } else {//恢复门禁权限
        accessOperat("/AcsAuthorization/unfreezeAccess",userId,function(result){
            if (result.returnCode == "0") {
                freezeUserOpt(userId);//解冻账号
            }else {
                tipModal("icon-cross", "门禁权限恢复失败");
            }
        })
    }
    $("#modalFreeze").modal("hide");
}

// 批量修改视频组权限
$(".btnVideoControl").on("click", function () {
    var batchArr = [];
    if(isChinamobileSelect == "0"){//内部用户
        $("#tab1 .chkUser").each(function (index, e) {
            if (e.checked == true) {
                batchArr.push(e.value);
            }
        });
    }else{//外部用户
        $("#tab2 .chkUser").each(function (index, e) {
            if (e.checked == true) {
                batchArr.push(e.value);
            }
        });
    }
    //将数据传入表单
    $("#parkUserIdBatch").val(batchArr.toString());
    if (batchArr.length == 0) {
        tipModal("icon-cross", "请选择人员");
        return false;
    }
    if (batchArr.length != 0) {
        for (var i = 0; i < batchArr.length; i++) {
            if (batchArr[i] == "") {
                tipModal("icon-cross", "请选择人员");
                return false;
            }
        }
    }

    // 清空视频组勾选
    $(".videolist.videolistBatch .t-tag-category").each(function () {
        $("this").removeClass('selected');
    });
    $("#editGroup").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
    $(window).on('resize', centerModal());
});

//确定修改视频组权限
$("#btnEditGroup").click(function () {
    var selectGuardUser = $("#parkUserIdBatch").val();
    var groupsArr = [];
    $(".videolist.videolistBatch .t-tag-category.selected").each(function () {
        groupsArr.push($(this).attr('data-id'))
    });

    // PostForm("/cwp/front/sh/videoGroup!execute", "uid=v011&parkUserId=" + selectGuardUser + "&idStr=" + groupsArr.toString(), "", function (result) {
    //     if (result.returnCode == 0) {
    //         tipModal("icon-checkmark", "视频权限修改成功");
    //     } else {
    //         tipModal("icon-cross", "视频权限修改失败");
    //     }
    // }, '', 'frm');
    $.getJSON('/cwp/src/json/user/user_videoGroup_v011.json',function(result){
        if (result.returnCode == 0) {
            tipModal("icon-checkmark", "视频权限修改成功");
        } else {
            tipModal("icon-cross", "视频权限修改失败");
        }
    })
    $("#editGroup").modal("hide");
});

//门禁组选择样式
$(document).on("click", ".access .t-tag-category", function () {
    if ($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    }
    else {
        $(this).addClass("selected");
    }
});

//冻结解冻
$(document).on("click", "#freeze-item .t-tag-category", function () {
    var erroricon = document.getElementById("noneChecked");
    erroricon.style.display = "none";
    if ($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    }
    else {
        $(this).addClass("selected");
    }
});

//批量修改门禁权限
var batchAdd = {userlist: []};
$(".btnAccessControl").on("click", function () {
    batchAdd = {userlist: []};
    var selectGuardUser = [];
    var selectUserCardNo = [];
    var selectUsertrueName = [];
    var selectUseremloyeeNo = [];
    var i = 0;
    if (isChinamobileSelect == 0) {
        $("#tab1 .chkUser").each(function (index, e) {
            if (e.checked == true) {
                batchAdd.userlist.push({
                    "uid": $(this).attr("data-emloyeeNo"),
                    "username": $(this).attr("data-name"),
                    "departmentid": '262',
                    "cardnumber": $(this).attr("data-carNo"),
                    "groupIds": []
                });
                selectGuardUser[i] = e.value;
                selectUserCardNo[i] = $(this).attr("data-carNo");
                selectUsertrueName[i] = $(this).attr("data-name");
                selectUseremloyeeNo[i] = $(this).attr("data-emloyeeNo");
                i++;
            }
        });
    } else {
        $("#tab2 .chkUser").each(function (index, e) {
            if (e.checked == true) {
                batchAdd.userlist.push({
                    "uid": $(this).attr("data-carNo"),
                    "username": $(this).attr("data-name"),
                    "departmentid": '262',
                    "cardnumber": $(this).attr("data-carNo"),
                    "groupIds": []
                });
                selectGuardUser[i] = e.value;
                selectUserCardNo[i] = $(this).attr("data-carNo");
                selectUsertrueName[i] = $(this).attr("data-name");
                selectUseremloyeeNo[i] = $(this).attr("data-emloyeeNo");
                i++;
            }
        });
    }
    //将数据传入表单
    $("#userArrayIds").val(selectGuardUser.toString());
    $("#cardNos").val(selectUserCardNo.toString());
    $("#employeeNos").val(selectUseremloyeeNo.toString());
    $("#truenames").val(selectUsertrueName.toString());
    if (selectGuardUser.length == 0) {
        tipModal("icon-cross", "请选择人员");
        return false;
    }
    if (selectGuardUser.length != 0) {
        for (var i = 0; i < selectGuardUser.length; i++) {
            if (selectGuardUser[i] == "") {
                tipModal("icon-cross", "请选择人员");
                return false;
            }
        }
    }
    if (selectUserCardNo.length != 0) {
        for (var i = 0; i < selectUserCardNo.length; i++) {
            if (selectUserCardNo[i] == "") {
                tipModal("icon-cross", "人员卡号不能为空");
                return false;
            }
        }
    }
    if (selectUsertrueName.length != 0) {
        for (var i = 0; i < selectUsertrueName.length; i++) {
            if (selectUsertrueName[i] == "") {
                tipModal("icon-cross", "人员卡号不能为空");
                return false;
            }
        }
    }
    if (selectUseremloyeeNo.length != 0) {
        for (var i = 0; i < selectUseremloyeeNo.length; i++) {
            if (selectUseremloyeeNo[i] == "") {
                tipModal("icon-cross", "人员编号不能为空");
                return false;
            }
        }
    }
    //获取门禁权限列表
    getAccessList();
    $("#editGuard").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
    $(window).on('resize', centerModal());

});

//确定修改门禁权限
$("#btnEditGuard").click(function () {
    var selectGuardUser = $("#userArrayIds").val();//被选中的用户Id组合
    var accessList =  getAccessArr();//选中的门禁id组合
    //tipModal("icon-checkmark", "门禁权限修改成功");
    //tipModal("icon-cross", "门禁权限修改失败");
    //$("#editGuard").modal("hide");
});